package xworker.gluon.netty;

import xworker.netty.NettySession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Client {
    private static long seq = 0;
    private static final Object lockObj = new Object();
    long id;
    String name;
    final List<Provider> providerList = new ArrayList<>();
    NettySession nettySession;

    public Client(){
        synchronized (lockObj) {
            seq++;
            id = seq;
        }
    }

    public void sendMessage(Object message) throws IOException {
        nettySession.sendMessage(message);
    }

    public boolean isClosed(){
        return nettySession == null || nettySession.isClosed();
    }

    public void addProvider(Provider provider){
        if(!providerList.contains(provider)){
            providerList.add(provider);
            provider.addClient(this);
        }
    }

    public void onClosed(){
        for(Provider provider : providerList){
            provider.removeClient(this);
        }
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Provider> getProviderList() {
        return providerList;
    }

    public void attach(NettySession session){
        session.setAttribute("client", this);
        this.nettySession = session;
    }

    public NettySession getNettySession() {
        return nettySession;
    }

    public static Client getClient(NettySession session){
        return (Client) session.getAttribute("client");
    }
}
